import requests
from requests.auth import HTTPBasicAuth

"""
requests模块是Python中用于发送HTTP请求的非常流行的第三方库。
它使得与Web服务的交互变得非常简单和直观，支持发送各种类型的HTTP请求（如GET、POST、PUT、DELETE等）。
requests模块以其易用性和功能丰富而广受欢迎，特别是在Web开发、数据爬取、API调用等场景中。
"""

response = requests.get("https://jsonplaceholder.typicode.com/posts/1")

# 状态码
print("[REQUESTS模块测试-GET请求] 请求状态码 {}".format(response.status_code))
# 响应体 JSON格式
print("[REQUESTS模块测试-GET请求] 请求响应体JSON格式", response.json(), sep="\n")
# 响应体 字符串格式
print("[REQUESTS模块测试-GET请求] 请求响应体字符串格式", response.text, sep="\n")

url = 'https://jsonplaceholder.typicode.com/posts'
data = {
    'title': 'foo',
    'body': 'bar',
    'userId': 1
}

# 发送JSON格式的数据
response = requests.post(url, json=data)
# 状态码
print("[REQUESTS模块测试-POST请求] 请求状态码 {}".format(response.status_code))
# 响应结果
print("[REQUESTS模块测试-POST请求] 请求响应体字符串格式", response.text, sep="\n")

# 添加请求头
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}

response = requests.get('https://jsonplaceholder.typicode.com/posts/1', headers=headers)
print(response.text)

# 发送带有参数的请求
params = {'userId': 1}
response = requests.get('https://jsonplaceholder.typicode.com/posts', params=params)
print(response.url)  # 输出请求的完整URL
print(response.json())

# 处理响应后的内容
response = requests.get('https://jsonplaceholder.typicode.com/posts/1')

print(response.status_code)  # 状态码
print(response.headers)  # 响应头
print(response.text)  # 原始文本内容
print(response.json())  # JSON内容
print(response.content)  # 二进制内容

try:
    response = requests.get('https://jsonplaceholder.typicode.com/posts/1', timeout=5)
    response.raise_for_status()  # 检查请求是否成功
except requests.exceptions.Timeout:
    print("请求超时")
except requests.exceptions.RequestException as e:
    print(f"请求发生错误: {e}")

# 文件上传
files = {'file': open('test.txt', 'rb')}
response = requests.post('https://httpbin.org/post', files=files)
print(response.text)

# 身份验证
response = requests.get('https://httpbin.org/basic-auth/user/pass', auth=HTTPBasicAuth('user', 'pass'))
print(response.status_code)
print(response.json())

# 错误处理
response = requests.get('https://httpbin.org/status/404')
try:
    response.raise_for_status()
except requests.exceptions.HTTPError as e:
    print(f"HTTP错误发生: {e}")
